package com.lagou.utils;

import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class FileUploadUtils {
    public static Map<String, String> fileUpload(MultipartFile file, HttpServletRequest request) throws IOException {
        // 1. 判断文件是否为空
        if(file.isEmpty()){
            throw new RuntimeException();
        }
        // 2. 获取项目部署路径
        String realPath = request.getServletContext().getRealPath("/");
        String webappsPath = realPath.substring(0, realPath.indexOf("ssm_web"));
        // 3. 获取原文件名
        String filename = file.getOriginalFilename();
        // 4. 新文件名
        String newFilename = System.currentTimeMillis() + filename.substring(filename.lastIndexOf("."));
        // 5. 上传文件
        String uploadPath = webappsPath + "upload\\";
        File filePath = new File(uploadPath, newFilename);
        //如果目录不存在就创建目录
        if(!filePath.getParentFile().exists()){
            filePath.getParentFile().mkdirs();
            System.out.println("创建目录：" + filePath);
        }
        //上传了文件
        file.transferTo(filePath);
        // 6. 将文件名和文件路径返回
        Map<String, String> map = new HashMap<>();
        map.put("fileName", newFilename);
        map.put("filePath", "http://localhost:8080/upload/" + newFilename);
        return map;
    }
}
